<?php

namespace app\admin\controller\store;

use app\common\controller\AdminController;
use app\common\service\store\GoodsCouponContactService;
use app\common\service\store\GoodsCouponService;
use app\common\service\store\GoodsService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\exception\ValidateException;

/**
 * @ControllerAnnotation(title="goods_coupon")
 */
class GoodsCoupon extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\store\GoodsCoupon();
    }

    /**
     * Author:Zhongyuan Lu
     * 添加优惠券
     * @return mixed|\think\response\Json
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();

            //验证参数
            try {
                validate(\app\validate\StoreCoupon::class)->batch(true)->check($post);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                $message = implode($e->getError(),',');
                return $this->error($message);
            }

            if ($post['coupon_price'] < 0 || $post['use_min_price'] < 0 || $post['integral'] < 0) {
                return $this->error('参数错误',[]);
            }

            if (!empty($post['discount']) && $post['discount'] < 0 || $post['discount'] > 100){
                return $this->error('折扣值只能在0到100之间');
            }

            //添加优惠券
            $data = GoodsCouponService::createCoupon($post);
            if ($data['code'] == 200) {
                return $this->success($data['message']);
            }
            return $this->error($data['message']);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        $goods_id = GoodsCouponContactService::getGoodsId($id);
        if (!empty($goods_id)) {
            $image = GoodsService::getGoodsImages($goods_id);
            $this->assign('image', $image);
        }
        $row['goods_id'] = implode(',',$goods_id);
        $row['start_time'] = date('Y-m-d',$row['start_time']).'T'.date('H:i');
        $row['end_time'] = date('Y-m-d',$row['end_time']).'T'.date('H:i');

        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }
}